from common import app,db
from models import Category,Stock
from flask import jsonify,render_template,request


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    print(path)
    return render_template('index.html')

@app.route('/app/category')
def category():
    session = db.session
    res = []
    # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
    category1s = session.query(Category).filter(Category.parent_id==0).all()
    for category1 in category1s:
        cat1_res = {}
        cat1_res['id'] = category1.id
        cat1_res['cate_name'] = category1.cate_name
        cat1_res['children'] = []
        category2s = session.query(Category).filter(Category.parent_id==category1.id).all()
        for category2 in category2s:
            cat2_res = {}
            cat2_res['id'] = category2.id
            cat2_res['cate_name'] = category2.cate_name
            cat2_res['children'] = []
            category3s = session.query(Category).filter(Category.parent_id==category2.id).all()
            for category3 in category3s:
                cat3_res = {}
                cat3_res['id'] = category3.id
                cat3_res['cate_name'] = category3.cate_name
                cat2_res['children'].append(cat3_res)
            cat1_res['children'].append(cat2_res)
        res.append(cat1_res)
    return jsonify(res)

@app.route('/app/user/profile')
def profile():
    return jsonify({"test":"helloword"})

@app.route('/app/stock')
def getStockList():
    cat_id = request.args.get('cat_id')
    stock_list  = db.session.query(Stock).filter(Stock.category_id==cat_id).all()
    result = []
    for stock in stock_list:
        result.append(stock.to_json())
    return jsonify(result)
 
 
if __name__ == '__main__':
    app.run(debug=True)
